import {defineComponent, reactive, onMounted, ref, onUnmounted, computed, watch} from 'vue';
import Draw from './draw'
import {useStore} from "vuex";
import {useWebSocketStore} from "@/store/websocket";

export default defineComponent({
  components: {
    Draw
  },
  setup() {
    // const drawTiming = ref(0)
    const wsStore = useWebSocketStore()
    const cdata = reactive({
      hours:[],
      temperature:[],
      humidity:[],
      wind:[],
      light:[]
    })
    // 从 store 获取 envParam 并映射到 cdata
    const envParam = computed(() => wsStore.envParam || []);

    // 定义 category_id 到 cdata 属性的映射关系
    const categoryMap = {
      1: 'temperature',
      2: 'humidity',
      3: 'wind',
      4: 'light',
    };
    const hourMap = ref<Array<number | string>>([]);
    // 处理 envParam 并更新 cdata
    const updateCdata = () => {
      // 清空数据
      Object.keys(cdata).forEach(key => {
        cdata[key] = [];
      });

      // 根据 category_id 分组数据
      envParam.value.forEach(item => {
        const targetKey = categoryMap[item.category_id];
        if (targetKey && cdata[targetKey]) {
          cdata[targetKey] = item.value_list;
          hourMap.value = item.time_list;
        }
      });
      if(hourMap.value=== []) return;
      if (Array.isArray(hourMap.value) ) {
        hourMap.value.forEach((timeItem, index) => {
          // 根据数据类型处理时间格式
          const timeLabel = typeof timeItem === 'number'
              ? `Hour ${index + 1}`
              : new Date(timeItem).toLocaleTimeString();
          cdata.hours.push(timeLabel);
        });
      } else {
        console.error('hourMap.value is not an array:', hourMap.value);
      }
      console.log(cdata,"环境cdata")
    };

    // 监听 envParam 变化
    watch(envParam, () => {
      updateCdata();
    }, { immediate: true });
    // methods

    // 生命周期
    // onMounted(() => {
    // })

    // onUnmounted(() => {
    // })

    return () => {
      return <div>
        <Draw cdata={cdata} />
      </div>
    }
  }
})